import os.path
import time

from PIL import Image
import pytesseract
import cv2 as cv
import cv2
import numpy as np
import matplotlib.pyplot as plt

image_base_path = "../temp_files/images/"
image_files = [
    "coor_x.png",
    "coor_y.png"
]

image_paths = [os.path.join(image_base_path, image_file) for image_file in image_files]


def extract():
    results = []
    for image_path in image_paths:
        print(image_path)
        start = time.time()
        img = cv.imread(image_path)
        text = pytesseract.image_to_string(Image.fromarray(img))
        end = time.time()
        print("耗时：", end - start)
        results.append(text)

    print(results)


def remove_background(image_path):
    # 加载原始图片
    image = cv2.imread(image_path)
    print("image:", image)
    # 创建一个与输入图片相同大小的空白画布
    masked_image = np.zeros(image.shape[:3], dtype=np.uint8)

    # 定义要提取的颜色范围（这里示意为红色）
    lower_color = (220, 220, 220)  # 最低阈值
    upper_color = (255, 255, 255)  # 最高阈值

    # 根据颜色范围生成二值化图像
    hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    binary_image = cv2.inRange(hsv_image, lower_color, upper_color)

    # 对二值化图像进行形态学操作，消除噪点
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    morphology_result = cv2.morphologyEx(binary_image, cv2.MORPH_OPEN, kernel)

    # 查找并标记连通区域
    contours, _ = cv2.findContours(morphology_result, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for contour in contours:
        x, y, w, h = cv2.boundingRect(contour)

        if w > image.shape[1] / 4 and h > image.shape[0] / 4:
            masked_image[y:y + h, x:x + w] = image[y:y + h, x:x + w]

    # 保存结果图片
    cv2.imwrite('../temp_files/images/test.png', masked_image)


def test_gray():
    img = cv.imread(image_paths[0])
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    print(type(img_gray))
    print(img_gray.shape)
    print(img_gray)
    img_gray = 255 * (img_gray != 255)
    # img_inv, thresh2 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)
    # images = [img, img_gray, thresh2]
    # for i in range(3):
    #     plt.subplot(1, 3, i + 1)
    #     plt.imshow(images[i], "gray")
    plt.imshow(img_gray, "gray")
    plt.show()
    cv2.imwrite(os.path.join(image_base_path, "coor_gray.png"), img_gray)


def upscale_image(image, scale):
    height, width = image.shape[:2]
    new_height = int(height * scale)
    new_width = int(width * scale)
    new_image = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_LINEAR)
    new_image = 255 * (new_image > 220)
    return new_image


def increase_res():
    import cv2

    # 读取原始图像并转换为灰度图像
    image_path = os.path.join(image_base_path, "coor_x.png")
    image = cv2.imread(image_path)
    upscaled = upscale_image(image, 8)
    print(upscaled.shape)
    plt.imshow(upscaled)
    plt.show()
    # 显示结果图像
    # cv2.imshow("Enhanced Image", enhanced_image)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
    result = os.path.join(image_base_path, "coor_upscaled.png")
    cv2.imwrite(result, upscaled)

# def show_img()

if __name__ == "__main__":
    # extract()
    # remove_background("../temp_files/images/coor_x.png")
    # test_gray()
    increase_res()